package firstping.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

import firstping.data.QnAPersistenceManager;
import firstping.model.Customer;
import firstping.model.Domain;

@SuppressWarnings("serial")
public class ForGotPasswordServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		String[] check = new String[4];
		req.setAttribute("check", check);
		
		req.setAttribute("title", "For got password");
		req.setAttribute("keyword", "account,monitoring domain,firstping,statistics site");
		req.setAttribute("description", "For got password.We provide web site monitoring to webmasters. Monitor your web site is availability 24 hours a day, 7 days a week with instant email alerts and weekly web site performance statistics.");
		
		try {
			req.getRequestDispatcher("/for_got_password.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");

		PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
		String email = req.getParameter("email");

		String[] check = new String[4];

		Query query = psm.newQuery(Customer.class);
		query.setFilter("email=='"+email+"'");
		@SuppressWarnings("unchecked")
		List<Customer> checks = (List<Customer>)query.execute();
		
		//check capchar
		String remoteAddr = req.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey("6Lf59ccSAAAAANK1ZHc5x_r4dfk6mZQTEJCvjFlo");

        String challenge = req.getParameter("recaptcha_challenge_field");
        String uresponse = req.getParameter("recaptcha_response_field");
        if(challenge == null)
        {
        	challenge = "b";
        }
        if(uresponse == null)
        {
        	uresponse = "a";
        }
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (!reCaptchaResponse.isValid()) {
        	check[1] = "Invalid Capcha";
        }
		
		if(checks.size() > 0 && check[1] == null)
		{
			Random random = new Random();
			int r = random.nextInt(100000);
			
			checks.get(0).setPassword(String.valueOf(r));
			psm=JDOHelper.getPersistenceManager(checks.get(0));
			psm.currentTransaction().begin();
			psm.makePersistent(checks.get(0));
			psm.currentTransaction().commit();
			
			Properties props = new Properties();
	        Session session = Session.getDefaultInstance(props, null);

	        String emails = "Firstping.com support";
	        String text = "We would like to provide a new password for your account at Firstping.com<br/><br/><b>Email : </b>"+email+"<br/><b>Password : </b>"+r;
	        
	        String msgBody = text;

	        try {
	            Message msg = new MimeMessage(session);
	            msg.setFrom(new InternetAddress("admin@firstping.com",emails));
	            msg.addRecipient(Message.RecipientType.TO,
	                             new InternetAddress(email,email));
	            msg.setSubject("For got password");
	            msg.setContent(msgBody, "text/html");
	            Transport.send(msg);
	           
	        } catch (AddressException e1) {
	            // ...
	        } catch (MessagingException e1) {
	            // ...
	        }
	        req.setAttribute("success", "For got password successfully .");
	        
		} else {
			if(checks.size() <= 0)
				check[0] = "Email does not exist !";
		}
		req.setAttribute("check", check);
		req.setAttribute("title", "For got password");
		req.setAttribute("keyword", "account,monitoring domain,firstping,statistics site");
		req.setAttribute("description", "For got password.We provide web site monitoring to webmasters. Monitor your web site is availability 24 hours a day, 7 days a week with instant email alerts and weekly web site performance statistics.");
        try {
			req.getRequestDispatcher("/for_got_password.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
